package form

import (
	"fmt"
	"time"
	"yunj/pkg/yunj/app/enum/admin/authenum"
	"yunj/pkg/yunj/core/builder/builderconsts"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/core/builder/form"
	"yunj/pkg/yunj/core/builder/form/field"
	"yunj/pkg/yunj/core/builder/form/field/action"
	"yunj/pkg/yunj/core/consts"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

func CommonFields(ctx *gin.Context, tab *builderdto.FormTab) (fields []form.FieldInterface, err error) {
	fields = []form.FieldInterface{
		field.NewTxt("txt", "文字描述...如：提示信息！这是一个温馨提示哦！"),
		field.NewLine("line1", "常规字段类型"),
		field.NewHidden("hidden", "隐藏域"),
		field.NewText("text", "单行文本框").SetVerify("max:10").SetGrid(12, 6, 6),
		field.NewPassword("password", "密码框").SetGrid(12, 6, 6),
		field.NewRadio("radio", "单选框").SetGrid(12, 6, 6).SetOptions([]builderdto.Option{{Value: "option1", Label: "选项一"}, {Value: "option2", Label: "选项二"}}),
		field.NewCheckbox("checkbox", "复选框").SetGrid(12, 6, 6).SetOptions([]builderdto.Option{{Value: "option1", Label: "选项一"}, {Value: "option2", Label: "选项二"}}),
		field.NewSelect("select", "下拉选框").SetGrid(12, 6, 6).SetOptions([]builderdto.Option{{Value: "option1", Label: "选项一"}, {Value: "option2", Label: "选项二"}}),
		field.NewArea("area", "地区联动").SetGrid(12, 6, 6),
		field.NewSwitch("switch", "开关").SetGrid(12, 4, 4),
		field.NewColor("color", "取色器").SetGrid(12, 4, 4),
		field.NewIcon("icon", "图标").SetGrid(12, 4, 4),
		field.NewImage("image", "图片上传").SetGrid(12, 6, 6),
		field.NewImage("images", "多图上传").SetGrid(12, 6, 6).SetMulti(true),
		field.NewFile("file", "文件上传").SetGrid(12, 6, 6),
		field.NewFile("files", "多文件上传").SetGrid(12, 6, 6).SetMulti(true),
		field.NewTextarea("textarea", "多行文本框").SetVerify("max:100"),
		field.NewEditor("editor", "富文本"),
		field.NewMarkdown("markdown", "Markdown"),
		field.NewLine("line2", "日期与时间"),
		field.NewDate("date", "日期").SetGrid(12, 3, 3).SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "昨天",
				Value: "()=>{return yunj.getDaysDateObj(-1);}",
			},
			{
				Text:  "今天",
				Value: "()=>{return new Date();}",
				//Value : "2024-08-08",
				//Value : "new Date()",
			},
			{
				Text:  "明天",
				Value: "()=>{return yunj.getDaysDateObj(1);}",
			},
			{
				Text:  "上个月",
				Value: "()=>{return yunj.getMonthsTodayDateObj(-1);}",
			},
			{
				Text:  "下个月",
				Value: "()=>{return yunj.getMonthsTodayDateObj(1);}",
			},
		}),
		field.NewDate("date_range", "日期范围").SetGrid(12, 3, 3).SetRange(" - ").SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "上周",
				Value: "()=>{return [yunj.getLastWeekStartDateObj(),yunj.getLastWeekEndDateObj()];}",
			},
			{
				Text:  "本周",
				Value: "()=>{return [yunj.getCurrWeekStartDateObj(),new Date()];}",
			},
			{
				Text:  "上月",
				Value: "()=>{return [yunj.getMonthsStartDateObj(-1),yunj.getMonthsEndDateObj(-1)];}",
			},
			{
				Text:  "本月",
				Value: "()=>{return [yunj.getCurrMonthStartDateObj(),new Date()];}",
			},
			{
				Text:  "最近一周",
				Value: "()=>{return [yunj.getDaysDateObj(-7),new Date()];}",
			},
			{
				Text:  "最近一月",
				Value: "()=>{return [yunj.getMonthsTodayDateObj(-1),new Date()];}",
			},
			{
				Text:  "最近三月",
				Value: "()=>{return [yunj.getMonthsTodayDateObj(-3),new Date()];}",
			},
		}),
		field.NewDatetime("datetime", "日期时间").SetGrid(12, 3, 3).SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "昨天",
				Value: "()=>{return yunj.getDaysDateObj(-1);}",
			},
			{
				Text:  "今天",
				Value: "()=>{return new Date();}",
			},
			{
				Text:  "明天",
				Value: "()=>{return yunj.getDaysDateObj(1);}",
			},
			{
				Text:  "上个月",
				Value: "()=>{return yunj.getMonthsTodayDateObj(-1);}",
			},
			{
				Text:  "下个月",
				Value: "()=>{return yunj.getMonthsTodayDateObj(1);}",
			},
		}),
		field.NewDatetime("datetime_range", "日期时间范围").SetGrid(12, 3, 3).SetRange(" - ").SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "上周",
				Value: "()=>{return [yunj.getLastWeekStartDateObj(),yunj.getLastWeekEndDateObj()];}",
			},
			{
				Text:  "本周",
				Value: "()=>{return [yunj.getCurrWeekStartDateObj(),new Date()];}",
			},
			{
				Text:  "上月",
				Value: "()=>{return [yunj.getMonthsStartDateObj(-1),yunj.getMonthsEndDateObj(-1)];}",
			},
			{
				Text:  "本月",
				Value: "()=>{return [yunj.getCurrMonthStartDateObj(),new Date()];}",
			},
			{
				Text:  "最近一周",
				Value: "()=>{return [yunj.getDaysDateObj(-7),new Date()];}",
			},
			{
				Text:  "最近一月",
				Value: "()=>{return [yunj.getMonthsTodayDateObj(-1),new Date()];}",
			},
			{
				Text:  "最近三月",
				Value: "()=>{return [yunj.getMonthsTodayDateObj(-3),new Date()];}",
			},
		}),
		field.NewYear("year", "年份").SetGrid(12, 3, 3).SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "去年",
				Value: "()=>{return yunj.getYearsDateObj(-1);}",
			},
			{
				Text:  "今年",
				Value: "()=>{return new Date();}",
			},
			{
				Text:  "明年",
				Value: "()=>{return yunj.getYearsDateObj(1);}",
			},
			{
				Text:  "三年前",
				Value: "()=>{return yunj.getYearsDateObj(-3);}",
			},
			{
				Text:  "三年后",
				Value: "()=>{return yunj.getYearsDateObj(3);}",
			},
		}),
		field.NewYear("year_range", "年份范围").SetGrid(12, 3, 3).SetRange(" - ").SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "去年",
				Value: "()=>{return [yunj.getYearsDateObj(-1),new Date()];}",
			},
			{
				Text:  "明年",
				Value: "()=>{return [new Date(),yunj.getYearsDateObj(1)];}",
			},
			{
				Text:  "近三年",
				Value: "()=>{return [yunj.getYearsDateObj(-3),new Date()];}",
			},
		}),
		field.NewYearMonth("year_month", "年月").SetGrid(12, 3, 3).SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "上个月",
				Value: "()=>{return yunj.getMonthsYearMonthDateObj(-1);}",
			},
			{
				Text:  "下个月",
				Value: "()=>{return yunj.getMonthsYearMonthDateObj(1);}",
			},
			{
				Text:  "去年本月",
				Value: "()=>{return yunj.getMonthsYearMonthDateObj(-12);}",
			},
		}),
		field.NewYearMonth("year_month_range", "年月范围").SetGrid(12, 3, 3).SetRange(" - ").SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "去年",
				Value: "()=>{return [yunj.getYearsStartDateObj(-1),yunj.getYearsEndDateObj(-1)];}",
			},
			{
				Text:  "明年",
				Value: "()=>{return [yunj.getYearsStartDateObj(1),yunj.getYearsEndDateObj(1)];}",
			},
			{
				Text:  "近三年",
				Value: "()=>{return [yunj.getMonthsYearMonthDateObj(-36),new Date()];}",
				//Value: ["2024-01","2024-02"],
			},
		}),
		field.NewTime("time", "时间").SetGrid(12, 3, 3).SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text: "09:00:00",
				//Value : "()=>{return yunj.getTimeDateObj(9);}",
				Value: "09:00:00",
			},
			{
				Text:  "12:00:00",
				Value: "()=>{return yunj.getTimeDateObj(12);}",
			},
			{
				Text:  "17:00:00",
				Value: "()=>{return yunj.getTimeDateObj(17);}",
			},
		}),
		field.NewTime("time_range", "时间范围").SetGrid(12, 3, 3).SetRange(" - ").SetShortcuts([]builderdto.FormDateShortcut{
			{
				Text:  "9-12点",
				Value: "()=>{return [yunj.getTimeDateObj(9),yunj.getTimeDateObj(12)];}",
			},
			{
				Text:  "13-17点",
				Value: "()=>{return [yunj.getTimeDateObj(13),yunj.getTimeDateObj(17)];}",
			},
		}),
		field.NewLine("line3", "下拉搜索"),
		field.NewDropdownSearch("dropdownSearchOptions", "下拉搜索-单选-已知数据").SetGrid(12, 6, 6).SetOptions([]builderdto.Option{
			{Value: 1, Label: "小王"},
			{Value: 2, Label: "小李"},
			{Value: 3, Label: "小张"},
			{Value: 4, Label: "小梁"},
			{Value: 5, Label: "小汤"},
		}),
		field.NewDropdownSearch("dropdownSearchMultiOptions", "下拉搜索-多选-已知数据").SetGrid(12, 6, 6).SetMulti(true).SetOptions([]builderdto.Option{
			{Value: 1, Label: "小王"},
			{Value: 2, Label: "小李"},
			{Value: 3, Label: "小张"},
			{Value: 4, Label: "小梁"},
			{Value: 5, Label: "小汤"},
		}),
		field.NewDropdownSearch("dropdownSearchOptionsApi", "下拉搜索-单选-接口请求数据").SetGrid(12, 6, 6).SetOptionsApi(util.BuildAdminUrl("/demo/form/dropdownSearchOptions", map[string]any{"originLocation": util.QueryUint8Param(ctx, "originLocation", authenum.TYPE_SIDEBAR_MENU)})),
		field.NewDropdownSearch("dropdownSearchMultiOptionsApi", "下拉搜索-多选-接口请求数据").SetGrid(12, 6, 6).SetMulti(true).SetOptionsApi(util.BuildAdminUrl("/demo/form/dropdownSearchOptions", map[string]any{"originLocation": util.QueryUint8Param(ctx, "originLocation", authenum.TYPE_SIDEBAR_MENU)})),

		field.NewLine("line4", "树形"),
		field.NewTreeRadio("tree_radio", "树-单选").SetGrid(12, 6, 6).SetNodes([]*builderdto.FormTreeCheckNode{
			{Id: 1, Pid: 0, Name: "节点一"},
			{Id: 2, Pid: 0, Name: "节点二"},
			{Id: 3, Pid: 1, Name: "节点三"},
			{Id: 4, Pid: 3, Name: "节点四", Checked: true, Readonly: true},
			{Id: 5, Pid: 2, Name: "节点五"},
			{Id: 6, Pid: 2, Name: "节点六"},
		}),
		field.NewTreeRadio("tree_radio_last_checked", "树-单选-末级可选").SetGrid(12, 6, 6).SetLastChecked(true).SetNodes([]*builderdto.FormTreeCheckNode{
			{Id: 1, Pid: 0, Name: "节点一"},
			{Id: 2, Pid: 0, Name: "节点二"},
			{Id: 3, Pid: 1, Name: "节点三"},
			{Id: 4, Pid: 3, Name: "节点四", Checked: true, Readonly: true},
			{Id: 5, Pid: 2, Name: "节点五"},
			{Id: 6, Pid: 2, Name: "节点六"},
		}),
		field.NewTreeCheckbox("tree_checkbox", "树-复选").SetGrid(12, 6, 6).SetNodes([]*builderdto.FormTreeCheckNode{
			{Id: 1, Pid: 0, Name: "节点一"},
			{Id: 2, Pid: 0, Name: "节点二"},
			{Id: 3, Pid: 1, Name: "节点三"},
			{Id: 4, Pid: 3, Name: "节点四", Checked: true, Readonly: true},
			{Id: 5, Pid: 2, Name: "节点五"},
			{Id: 6, Pid: 2, Name: "节点六"},
		}),
		field.NewTreeCheckbox("tree_checkbox_last_checked", "树-复选-末级可选").SetGrid(12, 6, 6).SetLastChecked(true).SetNodes([]*builderdto.FormTreeCheckNode{
			{Id: 1, Pid: 0, Name: "节点一"},
			{Id: 2, Pid: 0, Name: "节点二"},
			{Id: 3, Pid: 1, Name: "节点三"},
			{Id: 4, Pid: 3, Name: "节点四", Checked: true, Readonly: true},
			{Id: 5, Pid: 2, Name: "节点五"},
			{Id: 6, Pid: 2, Name: "节点六"},
		}),
		field.NewTreeEdit("tree_edit", "树-编辑").SetGrid(12, 6, 6).SetNodes([]*builderdto.FormTreeEditNode{
			{Id: 1, Pid: 0, Name: "衣服", Readonly: true},
			{Id: 2, Pid: 1, Name: "衬衣"},
			{Id: 3, Pid: 1, Name: "短袖", DisableSort: true},
			{Id: 4, Pid: 0, Name: "帽子"},
			{Id: 5, Pid: 4, Name: "遮阳帽"},
			{Id: 6, Pid: 0, Name: "手套"},
		}).SetActions([]action.ActionInterface{
			action.NewOpenPopup("edit", "编辑").SetClass("layui-icon-edit").SetUrl("/edit").SetConfirmFormFields(field.NewTxt("tips", "确认这么做？")),
			action.NewRename(), action.NewRemove(),
		}),
		field.NewTreeEdit("tree_edit_sort", "树-编辑-可排序").SetGrid(12, 6, 6).SetSort(builderconsts.FORM_TREE_SORT_YES).SetNodes([]*builderdto.FormTreeEditNode{
			{Id: 1, Pid: 0, Name: "衣服", Readonly: true},
			{Id: 2, Pid: 1, Name: "衬衣"},
			{Id: 3, Pid: 1, Name: "短袖", DisableSort: true},
			{Id: 4, Pid: 0, Name: "帽子"},
			{Id: 5, Pid: 4, Name: "遮阳帽"},
			{Id: 6, Pid: 0, Name: "手套"},
		}).SetActions([]action.ActionInterface{
			action.NewOpenPopup("edit", "编辑").SetClass("layui-icon-edit").SetUrl("/edit").SetConfirmFormFields(field.NewTxt("tips", "确认这么做？")),
			action.NewRename(), action.NewRemove(),
		}),

		field.NewLine("line5", "表格"),
		field.NewTable("table", "表格").SetGrid(12, 6, 6).SetAddAction(true).SetDelAction(true).SetCols([]builderdto.FormTableCol{
			{Title: "姓名", Field: "name", Verify: "required"},
			{Title: "年龄", Field: "age"},
		}),
		field.NewTable("table_edit", "表格-编辑-排序").SetGrid(12, 6, 6).SetAddAction(true).SetDelAction(true).
			SetSortAction(true).SetCols([]builderdto.FormTableCol{
			{Title: "姓名", Field: "name", Verify: "required"},
			{Title: "年龄", Field: "age"},
		}),

		field.NewLine("line6", "自定义字段"),
		field.NewCustom("custom").SetReadonly(true).SetHtmlFunc(func(field *field.Custom) (html string, err error) {
			var formId string
			formId, err = field.GetFormId()
			if err != nil {
				return
			}
			fmt.Println("自定义字段获取FormId", formId)
			html = "<p style:\"color:red\">这是自定义字段测试文本...</p>"
			return
		}),
	}

	for _, f := range fields {
		if err = f.GetError(); err != nil {
			return
		}
		var title string
		title, err = f.GetFieldTitle()
		if err != nil {
			return
		}

		switch tab.Code {
		case "required":
			if title != "" {
				f.SetFieldTitle(title + "（必填）")
			}
			f.AddFieldVerify("required")
			setCommonFieldDefault(f)
		case "default":
			if title != "" {
				f.SetFieldTitle(title + "（默认）")
			}
			setCommonFieldDefault(f)
		case "readonly":
			if title != "" {
				f.SetFieldTitle(title + "（只读）")
			}
			f.SetFieldReadonly(true)
			setCommonFieldDefault(f)
		}
		id, _ := f.GetFieldId()
		err = f.SetFieldId(tab.Code + "_" + id)
		if err != nil {
			return
		}
	}

	return
}

// 设置公共字段默认值
func setCommonFieldDefault(f form.FieldInterface) {
	var defValue any
	typ, _ := f.GetFieldType()
	switch typ {
	case "Hidden":
		defValue = "123"
	case "Text":
		defValue = "这是单行文本框哦"
	case "Password":
		defValue = "123456"
	case "Radio":
		defValue = "option2"
	case "Checkbox":
		defValue = []string{"option1", "option2"}
	case "Select":
		defValue = "option2"
	case "Area":
		defValue = map[string]string{"province": "110000", "city": "110100", "district": "110101"}
	case "Switch":
		defValue = "on"
	case "Color":
		defValue = "#ffff00"
	case "Icon":
		defValue = "yunj-icon-sub"
	case "Image":
		image, ok := f.(*field.Image)
		if ok {
			if image.Multi {
				defValue = []string{consts.IMG_URI, consts.IMG_URI}
			} else {
				defValue = consts.IMG_URI
			}
		}
	case "File":
		file, ok := f.(*field.File)
		if ok {
			if file.Multi {
				defValue = []string{consts.TEST_FILE_URL, consts.TEST_FILE_URL}
			} else {
				defValue = consts.TEST_FILE_URL
			}
		}
	case "Textarea":
		defValue = "这是多行文本框哦"
	case "Editor":
		defValue = "<h1>这是富文本编辑器哦</h1>"
	case "Markdown":
		defValue = "## 这是Markdown编辑器哦"
	case "Date":
		date, ok := f.(*field.Date)
		if ok {
			if date.Range == "" {
				defValue = time.Now().Format("2006-01-02")
			} else {
				defValue = map[string]string{"start": time.Now().Add(-24 * time.Hour).Format("2006-01-02"), "end": time.Now().Format("2006-01-02")}
			}
		}
	case "Datetime":
		datetime, ok := f.(*field.Datetime)
		if ok {
			if datetime.Range == "" {
				defValue = time.Now().Format("2006-01-02 15:04:05")
			} else {
				defValue = map[string]string{"start": time.Now().Add(-24 * time.Hour).Format("2006-01-02 15:04:05"), "end": time.Now().Format("2006-01-02 15:04:05")}
			}
		}
	case "Year":
		year, ok := f.(*field.Year)
		if ok {
			if year.Range == "" {
				defValue = time.Now().AddDate(-1, 0, 0).Year()
			} else {
				defValue = map[string]any{"start": time.Now().AddDate(-1, 0, 0).Year(), "end": time.Now().Year()}
			}
		}
	case "YearMonth":
		yearMonth, ok := f.(*field.YearMonth)
		if ok {
			if yearMonth.Range == "" {
				defValue = time.Now().Format("2006-01")
			} else {
				defValue = map[string]any{"start": time.Now().AddDate(0, -1, 0).Format("2006-01"), "end": time.Now().Format("2006-01")}
			}
		}
	case "Time":
		timeField, ok := f.(*field.Time)
		if ok {
			if timeField.Range == "" {
				defValue = time.Now().Format("15:04:05")
			} else {
				defValue = map[string]any{"start": "00:00:00", "end": time.Now().Format("15:04:05")}
			}
		}
	case "DropdownSearch":
		dropdownSearch, ok := f.(*field.DropdownSearch)
		if ok {
			if dropdownSearch.Multi {
				defValue = []int{1, 2}
			} else {
				defValue = 1
			}
		}
	case "TreeRadio":
		defValue = 5
	case "TreeCheckbox":
		defValue = []int{5, 6}
	case "Table":
		defValue = []map[string]any{
			{"name": "小王", "age": 18},
			{"name": "小李", "age": 20},
		}

	}
	f.SetFieldDefault(defValue)
}
